package com.jinlejia.erp.ui.customer;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.SearchCustomerAdapter;
import com.jinlejia.erp.adapter.SearchHistoryAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.BaseActivity;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.CustomerRentHistoryBean;
import com.jinlejia.erp.bean.CustomerShsHistoryBean;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.ActivitySearchCustomerBinding;
import com.jinlejia.erp.ui.common.CommonDeleteDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DbUtil;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 搜索客源
 */
public class SearchCustomerActivity extends BaseActivity {
    SearchCustomerAdapter adapter;
    SearchHistoryAdapter historyAdapter;

    JSONObject jsonObject = new JSONObject();

    private ActivitySearchCustomerBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_search_customer);
        binding.btBack.setOnClickListener(this::onClick);
        binding.btClear.setOnClickListener(this::onClick);
        initView();
        jsonObject.put("isPublic",getIntent().getStringExtra("isPublic"));
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_clear:
                binding.etSearchText.setText("");
                break;
            default:
                break;
        }
    }

    private void initView() {
        binding.etSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    binding.btClear.setVisibility(View.VISIBLE);
                    jsonObject.put("nameKey",s.toString());

                    if(getIntent().getStringExtra("type").equals("shs")){
                        searchData(ApiConfig.CUSTOMER_SEARCH);
                    }else{
                        searchData(ApiConfig.CUSTOMER_RENT_SEARCH);
                    }
                } else {
                    binding.btClear.setVisibility(View.INVISIBLE);
                }
            }
        });

        binding.yfrvSearchResult.setHasFixedSize(true);
        binding.yfrvSearchResult.setLayoutManager(new LinearLayoutManager(this));

        //搜索历史
        ArrayList historyList = new ArrayList();
        if (getIntent().getStringExtra("type").equals("rent")) {
            historyList.addAll(DbUtil.getDB(SearchCustomerActivity.this).single().query(CustomerRentHistoryBean.class));
        } else if (getIntent().getStringExtra("type").equals("shs")) {
            historyList.addAll(DbUtil.getDB(SearchCustomerActivity.this).single().query(CustomerShsHistoryBean.class));
        }
        Collections.reverse(historyList);
        historyAdapter = new SearchHistoryAdapter(historyList);
        if (historyList.size() > 0)
            historyAdapter.addFooter("清空历史");
        binding.yfrvSearchResult.setAdapter(historyAdapter);
        historyAdapter.setOnFooterViewClickListener((view, o) -> {

            CommonDeleteDialog dialog = new CommonDeleteDialog(SearchCustomerActivity.this, "清空历史", "确定清空历史记录?");
            dialog.show();
            dialog.setConfirmListener(() -> {
                if (getIntent().getStringExtra("type").equals("rent")) {
                    DbUtil.getDB(SearchCustomerActivity.this).single().deleteAll(CustomerRentHistoryBean.class);
                } else if (getIntent().getStringExtra("type").equals("shs")) {
                    DbUtil.getDB(SearchCustomerActivity.this).single().deleteAll(CustomerShsHistoryBean.class);
                }
                historyAdapter.getData().clear();
                historyAdapter.changeMode(YfListMode.MODE_EMPTY);
            });

        });
        historyAdapter.setOnItemClickListener((view, o) -> {
            if (getIntent().getStringExtra("type").equals("rent")) {
                CustomerRentHistoryBean crhb = new CustomerRentHistoryBean(((CustomerRentHistoryBean) o).getName());
                DbUtil.getDB(SearchCustomerActivity.this).single().delete(WhereBuilder.create(CustomerRentHistoryBean.class, "name=?", new String[]{crhb.getName()}));
                DbUtil.getDB(SearchCustomerActivity.this).single().save(crhb);
                EventBus.getDefault().post(crhb.getName(), "TAG_SEARCH_RENT");
            } else if (getIntent().getStringExtra("type").equals("shs")) {
                CustomerShsHistoryBean cshb = new CustomerShsHistoryBean(((CustomerShsHistoryBean) o).getName());
                DbUtil.getDB(SearchCustomerActivity.this).single().delete(WhereBuilder.create(CustomerShsHistoryBean.class, "name=?", new String[]{cshb.getName()}));
                DbUtil.getDB(SearchCustomerActivity.this).single().save(cshb);
                EventBus.getDefault().post(cshb.getName(), "TAG_SEARCH_SHS");
            }
            finish();
        });


        ArrayList list = new ArrayList();
        adapter = new SearchCustomerAdapter(list,"");
        binding.yfrvSearchResult.addItemDecoration(new RecycleViewDivider(
                SearchCustomerActivity.this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        adapter.setOnItemClickListener((view, o) -> {
            if( getIntent().getStringExtra("type").equals("shs") ){
                //买卖
                EventBus.getDefault().post(o.toString(),"TAG_SEARCH_SHS");
                CustomerShsHistoryBean cshb = new CustomerShsHistoryBean(o.toString());
                ArrayList<CustomerShsHistoryBean> shbList = DbUtil.getDB(SearchCustomerActivity.this).single().query(CustomerShsHistoryBean.class);
                if (shbList.size() == 20) {
                    //数量达到20，删除第一个
                    DbUtil.getDB(SearchCustomerActivity.this).single().delete(shbList.get(0));
                }
                if (DbUtil.getDB(SearchCustomerActivity.this).single().query(new QueryBuilder<>(CustomerShsHistoryBean.class)
                        .whereEquals("name", cshb.getName())).size() > 0)
                    //已经存在，先删除再存
                    DbUtil.getDB(SearchCustomerActivity.this).single().delete(WhereBuilder.create(CustomerShsHistoryBean.class, "name=?", new String[]{cshb.getName()}));
                DbUtil.getDB(SearchCustomerActivity.this).single().save(cshb);
            }else{
                //租赁
                EventBus.getDefault().post(o.toString(),"TAG_SEARCH_RENT_CUSTOMER");
                CustomerRentHistoryBean crhb = new CustomerRentHistoryBean(o.toString());
                ArrayList<CustomerRentHistoryBean> shbList = DbUtil.getDB(SearchCustomerActivity.this).single().query(CustomerRentHistoryBean.class);
                if (shbList.size() == 20) {
                    //数量达到20，删除第一个
                    DbUtil.getDB(SearchCustomerActivity.this).single().delete(shbList.get(0));
                }
                if (DbUtil.getDB(SearchCustomerActivity.this).single().query(new QueryBuilder<>(CustomerRentHistoryBean.class)
                        .whereEquals("name", crhb.getName())).size() > 0)
                    //已经存在，先删除再存
                    DbUtil.getDB(SearchCustomerActivity.this).single().delete(WhereBuilder.create(CustomerRentHistoryBean.class, "name=?", new String[]{crhb.getName()}));
                DbUtil.getDB(SearchCustomerActivity.this).single().save(crhb);
            }
            finish();
        });
    }

    private void searchData( String url ){
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(SearchCustomerActivity.this, response,adapter)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
                            //数据列表
                            ArrayList<String> list = JSON.parseObject(data.toString(), new TypeReference<ArrayList<String>>() {
                            });
                            adapter.setWord(jsonObject.getString("nameKey"));
                            adapter.setData(list);
                            binding.yfrvSearchResult.setAdapter(adapter);
                        }
                    }
                });
    }
}
